#!/usr/bin/env python
#Code Runner 插件目前无法识别 Linux 格式 Shebang。

import re
import sys
import os
from docx import Document

if __name__ == '__main__':
    #没传参数就输入 传了就直接用命令行参数 只看第一个参数
    if len(sys.argv) == 1:
        docxPath = input('输入docx文件目录:')
    else:
        docxPath = sys.argv[1]

    #没有文件就退出
    if not os.path.exists(docxPath):
        print(f'error: no such file \'{docxPath}\'')
        sys.exit()

    #获取文件名+_new就是新文件名
    baseName = os.path.basename(docxPath)
    #查看该文件后缀是不是docx
    if docxPath[-5 :] != '.docx':
        print(f'error: the file \'{baseName}\' is not a docx file')
        sys.exit()

    docx = Document(docxPath)
    html = []
    heading = re.compile('Heading [1-6]')
    paras = (docx.paragraphs)

    for i in range(len(paras)):
        paraText = ''
        paraFont = paras[i].style.font
        #对paragraph中各个run对象判断是否加粗 斜体 然后将文本连接成该段
        runs = paras[i].runs
        for j in range(len(runs)):
            runText = runs[j].text
            runFont = runs[j].font
            #为None的时候考虑样式中的默认字体
            if runs[j].font.bold or (runFont.bold == None and paraFont.bold):
                runText = '<b>' + runText + '</b>'

            if runs[j].font.italic or (runFont.italic == None and paraFont.italic):
                runText = '<i>' + runText + '</i>'

            paraText += runText

        # 如果是标题就插入对应的tag,否则用<p></p> 顺便加点缩进好看
        if heading.match(paras[i].style.name):
            index = int(paras[i].style.name[8])
            html.append('\t\t' + f'<h{index}>' + paraText + f'</h{index}>' + '\n')
        else:
            html.append('\t\t<p>' + paraText + '</p>\n')

    with open(f'{baseName[ : -5]}_new.html', 'w', encoding='UTF-8') as handler:
        handler.write("<!DOCTYPE html>\n<html>\n\t<body>\n")
        handler.writelines(html)
        handler.write("\t</body>\n</html>")